﻿using PuppeteerSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Formats.Asn1.AsnWriter;

namespace Q.Spider.Core.Models
{
    /// <summary>
    /// 配置实体类
    /// </summary>
    public class Config
    {
        public Config() {
            ConfigureLaunchOptions(null, null);
        }

        /// <summary>
        /// 引擎是否加载图片，如为true会浪费大量带宽和内存
        /// </summary>
        public bool EngineIsLoadImage { get; set; }

        /// <summary>
        /// 是否开启引擎无头模式
        /// </summary>
        public bool? EngineIsHeadless { get; set; } = true;


        /// <summary>
        /// redis连接字符串，填写了此字段意味着启动了分布式爬虫功能
        /// </summary>
        public string? RedisConnStr { get; set; }


        /// <summary>
        /// 一个请求最大重试次数
        /// </summary>
        public int RequestMaxRetryCount { get; set; }


        /// <summary>
        /// 代理地址
        /// </summary>
        public string? Proxy { get; set; }


        /// <summary>
        /// 获取新代理func
        /// </summary>
        public Func<QSpiderCore, Task<string>>? GetNewProxyAsync { get; set; }

        /// <summary>
        /// Redis表序号
        /// </summary>
        public int RedisDatabase { get; set; } = 0;

        public LaunchOptions PuppeteerLaunchOptions { get; set; }

        /// <summary>
        /// 配置Puppeteer
        /// </summary>
        /// <param name="configArgs">配置args</param>
        /// <param name="configOptions">配置LaunchOptions</param>
        /// <returns></returns>
        public Config ConfigureLaunchOptions(
           Action<List<string>>? configArgs, Action<LaunchOptions>? configOptions)
        {
            PuppeteerLaunchOptions = new();
            var args = new List<string>();
            if (!string.IsNullOrWhiteSpace(Proxy))
            {
                args.Add("--proxy-server=" + Proxy);
            }

            args.Add("--disable-infobars");
            args.Add("--no-sandbox");
            args.Add("--start-maximized");

            configArgs?.Invoke(args);

            
            var launchOptions = new LaunchOptions
            {
                DefaultViewport = new ViewPortOptions()
                {
                    Height = 800,
                    Width = 1300
                },
                Args = args.ToArray(),
            };

            configOptions?.Invoke(launchOptions);

            if (EngineIsHeadless != null)
            {
                launchOptions.Headless = EngineIsHeadless.Value;
            }

            PuppeteerLaunchOptions = launchOptions;
            return this;
        }

    }
}
